<template>
  <div class="picker-container">
    <van-field
      :label="label"
      :title-width="titleWidth"
      :border="border"
      :required="required"
      :value-class="valueClass"
      :focus="focus"
      input-class="picker-input__field"
      :size="size"
      :error="error"
      :error-message="errorMessage"
      :is-link="isLink"
    >
      <view
        slot="button"
        class="picker-input"
      >
        <picker
          mode="multiSelector"
          @change="onChange"
          @columnchange="onColumnChange"
          @cancel="onCancel"
          :value="indexArray"
          :range="dataColumn"
          ref="content"
        >
          <slot name="content">
            <view
              class="picker-input__value"
              v-if="showCheckText"
            > {{dataText}} </view>
            <view
              class="picker-input__placeholder"
              :class="[{'picker-input__error': error}]"
              v-else
            > {{placeholder}} </view>
          </slot>
        </picker>
      </view>
    </van-field>
  </div>
</template>

<script>
export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    label: {
      required: true,
      default: '字段名称'
    },
    // 选项数组
    items: {
      required: true,
      type: Object
    },
    // 选项数组
    dataType: {
      type: String,
      default: 'array'
    },
    // 默认选项
    defaultActive: [String, Number],
    // 分隔符
    splitChar: {
      type: String,
      default: '-'
    },
    // 显示层级
    showLevel: {
      type: Number,
      default: 2
    },
    titleWidth: {
      type: String
    },
    valueClass: {
      type: String
    },
    // 默认选项
    value: [String, Number],
    errorMessage: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    size: {
      type: String,
      default: ''
    },
    error: {
      type: Boolean,
      default: false
    },
    required: Boolean,
    border: {
      type: Boolean,
      default: true
    },
    isLink: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      active: null,
      indexArray: [],
      columns: [],
      topColumnText: [],
      showCheckText: false
    }
  },
  watch: {
    items: {
      handler (now) {
        console.log('items changed listen:', now)
        this.onMountPickerItems()
      },
      deep: true,
      immediate: true
    },
    value: {
      handler (now) {
        console.log('value changed listen:', now)
        this.active = now
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    topColumn () {
      var parents = []
      const items = this.items
      for (var i = 0, len = items.length; i < len; i++) {
        const item = items[i]
        if (!item.parent_id) {
          parents.push(item)
        }
      }
      return parents
    },
    parentColumn () {
      var parentsText = []
      var parents = []
      var columns = []
      const items = this.items
      for (var i = 0, len = items.length; i < len; i++) {
        const item = items[i]
        if (!item.parent_id) {
          parentsText.push(item.name)
          parents.push(item)
        }
        if (columns[item.parent_id]) {
          columns[item.parent_id].push(item)
        } else {
          columns[item.parent_id] = [item]
        }
      }
      this.topColumnText = parentsText
      console.log('parent column', columns)
      return columns
    },
    dataColumn () {
      var activeItem = this.getActiveItem()
      console.log('activeItem', activeItem)
      var rootId = 0
      if (activeItem.parent_id) {
        rootId = activeItem.parent_id
        for (let i = 0, len = this.topColumn.length; i < len; i++) {
          const item = this.topColumn[i]
          if (item.id === activeItem.parent_id && this.indexArray[0] !== i) {
            this.indexArray[0] = i
            break
          }
        }
      } else {
        rootId = activeItem.id
      }

      const children = this.parentColumn[rootId]
      const childrenText = children.map((item, index) => {
        if (activeItem && activeItem.id === item.id && this.indexArray[1] !== index) {
          this.indexArray[1] = index
        }
        return item.name
      })
      this.columns = [this.topColumn, children]
      const dataColumnText = [this.topColumnText, childrenText]

      return dataColumnText
    },
    dataText () {
      if (this.active) {
        this.showCheckText = true
        const columns = this.columns
        let checked = []
        for (let i = 0, len = this.indexArray.length; i < len; i++) {
          let columnItems = columns[i]
          if (columnItems) {
            let valueIndex = this.indexArray[i]
            checked.push(columnItems[valueIndex] && columnItems[valueIndex].name)
          }
        }
        return checked.join(this.splitChar)
      } else {
        this.showCheckText = false
        this.indexArray = [0, 0]
        return ''
      }
    }
  },
  onShow () {
    console.group('MultiPicker onShow')
    this.onMountPickerItems()
    console.log('value:', this.value)
    console.log('active:', this.active)
    console.groupEnd('MultiPicker onShow')
  },

  methods: {
    onMountPickerItems () {
      this.active = this.value
      if (this.active) {
        this.showCheckText = true
      } else {
        this.showCheckText = false
      }
    },
    getActiveItem () {
      var defaultItem = null
      for (let i = 0, len = this.items.length; i < len; i++) {
        const item = this.items[i]
        if (item.id === this.active) {
          return item
        }
        if (!defaultItem && item.parent_id === 0) {
          defaultItem = item
        }
      }
      return defaultItem
    },
    notice () {
      const checks = this.indexArray.slice()
      var active = this.active
      for (var i = 0; i < checks.length; i++) {
        var index = checks[i]
        active = this.columns[i][index].id
      }
      this.$emit('change', active)
    },
    onColumnChange (e) {
      console.log('PickerColumnChange', e.mp.detail)
      const { column, value } = e.mp.detail
      const checkedId = this.columns[column][value].id
      if (checkedId) {
        this.active = checkedId
      }
      if (column === 0 && checkedId) {
        this.$set(this.indexArray, 1, 0)
      }
      this.$set(this.indexArray, column, value)
    },
    onChange (e) {
      console.log('PickerChange', e.mp.detail)
      this.indexArray = e.mp.detail.value
      this.showCheckText = true
      this.notice()
    },
    onCancel (e) {
      console.log('PickerOnCancel', e.mp.detail)
    }
  }
}
</script>

<style lang="less">
.picker-input {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-family: UICTFontTextStyleBody;
  &__field {
    width: 0 !important;
  }
  &__placeholder {
    color: #c8c9cc;
  }
  &__error {
    color: #ee0a24;
  }
}
.van-field__body {
  justify-content: flex-end;
}
</style>